(function ($) {

AjaxSolr.ChartWidget = AjaxSolr.AbstractFacetWidget.extend({
  afterRequest: function () {
    //get start and end

    $(this.target).empty();
    var values = [];
    var maxCount = 9;
    for (var facet in this.manager.response.facet_counts.facet_dates[this.field]) {
        var count = parseInt(this.manager.response.facet_counts.facet_dates[this.field][facet]);
        if(facet != 'end' && facet!= 'gap') {
            values.push(count);
            if(maxCount<count) maxCount=count;
        }
    }
    var maxCount = 10+Math.round(maxCount/10)*10;
    var start = this.manager.store.get('facet.date.start').val().substr(0, 10);
    var end = this.manager.store.get('facet.date.end').val().substr(0, 10);

    for(var i = 0; i < values.length; i++) {
        //alert(values[i].name+" "+values[i].count);
    }
    var EXTENDED_MAP='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.';
    var EXTENDED_MAP_LENGTH = EXTENDED_MAP.length;
    var extendedEncode = function(arrVals, maxVal) {
        var chartData = 'e:';

        for(i = 0, len = arrVals.length; i < len; i++) {
            // In case the array vals were translated to strings.
            var numericVal = new Number(arrVals[i]);
            // Scale the value to maxVal.
            var scaledVal = Math.floor(EXTENDED_MAP_LENGTH * EXTENDED_MAP_LENGTH * numericVal / maxVal);

            if(scaledVal > (EXTENDED_MAP_LENGTH * EXTENDED_MAP_LENGTH) - 1) {
                chartData += "..";
            } else if (scaledVal < 0) {
                chartData += '__';
            } else {
                // Calculate first and second digits and add them to the output.
                var quotient = Math.floor(scaledVal / EXTENDED_MAP_LENGTH);
                var remainder = scaledVal - EXTENDED_MAP_LENGTH * quotient;
                chartData += EXTENDED_MAP.charAt(quotient) + EXTENDED_MAP.charAt(remainder);
            }
        }

      return chartData;
    }
    var src = 'http://chart.apis.google.com/chart?chxl=0:|'+start+'|'+end+'|1:|0|'+maxCount+'|2:|0|'+maxCount+'&chxs=0,00AA00,14,0.5,l,676767&chxt=x,r,y&chs=350x180&cht=lc&chd='+extendedEncode(values,maxCount)+'&chg=20,25&chls=1';
    $('<img/>').attr('src', src).appendTo(this.target);
  }
});

})(jQuery);